#include "esp_log.h"
#include "esp_http_server.h"
#include "server.h"
#include "camera_stream.h"
#include "ai_chat.h"

static const char *TAG = "SERVER";
static httpd_handle_t server = NULL;

// 摄像头和AI对话页面HTML内容
static const char* CAMERA_HTML = 
"<!DOCTYPE html>"
"<html>"
"<head>"
"<title>ESP32-CAM AI对话</title>"
"<meta name='viewport' content='width=device-width, initial-scale=1'>"
"<style>"
"body { font-family: Arial; margin: 20px; background-color: #f0f0f0; }"
".container { max-width: 800px; margin: 0 auto; background: white; padding: 20px; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }"
"h1 { text-align: center; color: #333; }"
"#cameraImage { width: 100%; border: 1px solid #ddd; border-radius: 5px; margin-bottom: 20px; }"
"#streamImage { width: 100%; border: 1px solid #ddd; border-radius: 5px; margin-bottom: 20px; }"
"#chatBox { border: 1px solid #ddd; height: 300px; overflow-y: scroll; padding: 10px; margin-bottom: 10px; border-radius: 5px; }"
"#userInput { width: calc(100% - 100px); padding: 10px; border: 1px solid #ddd; border-radius: 5px; }"
"#sendButton { width: 80px; padding: 10px; background: #4CAF50; color: white; border: none; border-radius: 5px; cursor: pointer; }"
".user-msg { text-align: right; color: blue; margin: 5px 0; }"
".ai-msg { text-align: left; color: green; margin: 5px 0; }"
"</style>"
"</head>"
"<body>"
"<div class='container'>"
"<h1>ESP32-CAM AI对话</h1>"
"<h3>静态图像 (每秒刷新)</h3>"
"<img id='cameraImage' src='/image' alt='摄像头图像'>"
"<h3>实时视频流</h3>"
"<img id='streamImage' src='/stream' alt='实时视频流'>"
"<div id='chatBox'></div>"
"<div>"
"<input type='text' id='userInput' placeholder='输入您的问题...'>"
"<button id='sendButton' onclick='sendMessage()'>发送</button>"
"</div>"
"</div>"
"<script>"
"// 自动刷新静态图像"
"setInterval(function() {"
"    document.getElementById('cameraImage').src = '/image?t=' + new Date().getTime();"
"}, 1000);"
""
"// 发送消息函数"
"function sendMessage() {"
"    var input = document.getElementById('userInput');"
"    var message = input.value.trim();"
"    if (message === '') return;"
"    "
"    // 显示用户消息"
"    displayMessage('您: ' + message, 'user-msg');"
"    input.value = '';"
"    "
"    // 发送到服务器"
"    fetch('/chat', {"
"        method: 'POST',"
"        headers: { 'Content-Type': 'application/json' },"
"        body: JSON.stringify({ message: message })"
"    })"
"    .then(response => response.json())"
"    .then(data => {"
"        displayMessage('AI: ' + data.response, 'ai-msg');"
"    })"
"    .catch(error => {"
"        displayMessage('AI: 抱歉，发生了错误: ' + error, 'ai-msg');"
"    });"
"}"
"// 显示消息函数"
"function displayMessage(text, className) {"
"    var chatBox = document.getElementById('chatBox');"
"    var msgDiv = document.createElement('div');"
"    msgDiv.className = className;"
"    msgDiv.textContent = text;"
"    chatBox.appendChild(msgDiv);"
"    chatBox.scrollTop = chatBox.scrollHeight;"
"}"
"</script>"
"</body>"
"</html>";

// 处理根页面请求
static esp_err_t camera_index_handler(httpd_req_t *req) {
    ESP_LOGI(TAG, "收到摄像头页面请求");
    httpd_resp_set_type(req, "text/html");
    return httpd_resp_send(req, CAMERA_HTML, HTTPD_RESP_USE_STRLEN);
}

// URI处理配置
static const httpd_uri_t camera_index = {
    .uri = "/",
    .method = HTTP_GET,
    .handler = camera_index_handler,
    .user_ctx = NULL
};

static const httpd_uri_t image = {
    .uri = "/image",
    .method = HTTP_GET,
    .handler = image_handler,
    .user_ctx = NULL
};

static const httpd_uri_t chat = {
    .uri = "/chat",
    .method = HTTP_POST,
    .handler = chat_handler,
    .user_ctx = NULL
};

static const httpd_uri_t stream = {
    .uri = "/stream",
    .method = HTTP_GET,
    .handler = stream_handler,
    .user_ctx = NULL
};

// 启动HTTP服务器
void start_http_server(void) {
    ESP_LOGI(TAG, "启动HTTP服务器...");
    
    httpd_config_t config = HTTPD_DEFAULT_CONFIG();
    config.server_port = 80;  // 使用80端口
    
    if (httpd_start(&server, &config) == ESP_OK) {
        // 注册URI处理器
        httpd_register_uri_handler(server, &camera_index);
        httpd_register_uri_handler(server, &image);
        httpd_register_uri_handler(server, &chat);
        httpd_register_uri_handler(server, &stream);
        
        ESP_LOGI(TAG, "HTTP服务器已启动，端口: %d", config.server_port);
    } else {
        ESP_LOGE(TAG, "启动HTTP服务器失败");
    }
}

// 停止HTTP服务器
void stop_http_server(void) {
    if (server) {
        httpd_stop(server);
        server = NULL;
        ESP_LOGI(TAG, "HTTP服务器已停止");
    }
}